import axios, { AxiosRequestConfig } from 'axios'

import {
  handleConfigureRequestHeader,
  handleConfigureAuth,
  handleAuthError,
  handleGeneralError,
  handleNetworkError
} from './tools'
import { ResponseData } from '@/api/interface'

const instance = axios.create({
    baseURL: "https://20.1.126.29",
    // baseURL: "http://localhost:8080",
    timeout: 5000,
})

instance.interceptors.request.use(config => {
  config = handleConfigureRequestHeader(config)
  config = handleConfigureAuth(config)
  return config
})

instance.interceptors.response.use(
  response => {
    // const res = response.data
    // if (!handleAuthError(res.code) || !handleGeneralError(res.code, res.message))
    //   return Promise.reject(new Error(res.message || 'Error'))
    return response
  },
  err => {
    handleNetworkError(err.response.status)
    return Promise.reject(err.response)
  }
)

export const request = <T>(props: AxiosRequestConfig): Promise<ResponseData<T>> => {
  return new Promise((resolve, reject) => {
    instance(props)
      .then(response => {
        const res = response.data
        if (!handleAuthError(res.code) || !handleGeneralError(res.code, res.message))
          return Promise.reject(new Error(res.message || 'Error'))
        resolve(res)
      })
      .catch(err => reject(err))
  })
}

export const MyRequest = <T>(props: AxiosRequestConfig): Promise<[any, ResponseData<T> | undefined]> => {
  return new Promise(resolve => {
    instance(props)
      .then(response => {
        const res = response.data
        if (!handleAuthError(res.code) || !handleGeneralError(res.code, res.message))
          return Promise.reject(new Error(res.message || 'Error'))
        resolve([null, res])
      })
      .catch(err => resolve([err, undefined]))
  })
}
